﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dapper;
using DapperExtensions;
using System.Data;
using Logistics.Model;
using DapperExtensions.Sql;
using DapperExtensions.Mapper;
using System.Reflection;

namespace Logistics_Dao
{
    public class ContractDao
    {
        private SqlGeneratorImpl sqlGenerator;
        public ContractDao()
        {
            var config = new DapperExtensionsConfiguration(typeof(AutoClassMapper<>), new List<Assembly>(), new MySqlDialect());
            sqlGenerator = new SqlGeneratorImpl(config);
            DapperExtensions.DapperExtensions.Configure(config);
        }
        public void Add(wuliu_contract_base contract)
        {
            using (IDbConnection conn = ConnectionHelper.OpenConnection())
            {

                conn.Insert<wuliu_contract_base>(contract);
            }
        }

        public PageData<wuliu_contract_base> GetList(IPredicate predicate, int page, int pageSize)
        {
            IList<ISort> sort = new List<ISort>
                                    {
                                        Predicates.Sort<wuliu_contract_base>(p => p.id,false)
                                    };
            var pageData = new PageData<wuliu_contract_base>();
            using (var conn = ConnectionHelper.OpenConnection())
            {
                pageData.TotalNum = conn.Count<wuliu_contract_base>(predicate);
                pageData.Items = conn.GetPage<wuliu_contract_base>(predicate, sort, page, pageSize).ToList();
                pageData.CurrentPage = page;
                pageData.TotalPageCount = pageData.TotalNum % pageSize == 0 ? pageData.TotalNum / pageSize : pageData.TotalNum / pageSize + 1;
            }
            return pageData;
        }

        public PageData<DataTable> GetContractList(IPredicate predicate, int pageIndex, int pageSize)
        {
          
            IList<ISort> sort = new List<ISort>
                                    {
                                        Predicates.Sort<wuliu_contract_base>(p => p.id,true)
                                    };
            var sql = @" from wuliu_contract_base  LEFT JOIN wuliu_wlcompany_business   ON wuliu_contract_base.wuliu_id=wuliu_wlcompany_business.wuliu_id
                         LEFT JOIN wuliu_wlcompany_base on wuliu_contract_base.wuliu_id=wuliu_wlcompany_base.wuliu_id where 1=1 ";

            using (var conn = ConnectionHelper.OpenConnection())
            {
                var pageData = new PageData<DataTable>();
                DynamicParameters dynamicParameters = new DynamicParameters();
                var whereSql = GetWhereSql(predicate, dynamicParameters);
                if (!string.IsNullOrEmpty(whereSql))
                {
                    sql += " and " + whereSql;
                }
                var num = conn.ExecuteScalar<int>("select count(1) " + sql, dynamicParameters);

                sql += "order by wuliu_contract_base.id DESC limit @pageIndex,@pageSize";
                //dynamicParameters.AddDynamicParams(pickParam);
                dynamicParameters.Add("pageIndex", pageIndex * pageSize);
                dynamicParameters.Add("pageSize", pageSize);
                //var count = conn.Count<wuliu_bid_load>(predicate);
                var data = conn.Query("select wuliu_contract_base.id as baseid,wuliu_wlcompany_business.*,wuliu_wlcompany_base.phone,wuliu_wlcompany_base.`name` " + sql, dynamicParameters);
                pageData.DataObj = data;
                pageData.TotalNum = num;
                pageData.CurrentPage = pageIndex;
                pageData.TotalPageCount = num % pageSize == 0 ? num / pageSize : num / pageSize + 1;
                return pageData;
            }
        }

        private string GetWhereSql(IPredicate predicate, DynamicParameters dynamicParameters)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            var wherSql = predicate.GetSql(sqlGenerator, parameters);

            foreach (var parameter in parameters)
            {
                dynamicParameters.Add(parameter.Key, parameter.Value);
            }
            return wherSql;
        }


        /// <summary>
        /// 判断记录是否存在
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int IsExitNum(wuliu_contract_base model)
        {
            using (var conn = ConnectionHelper.OpenConnection())
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("select count(1) ");
                strSql.Append(" FROM wuliu_contract_base  where 1=1 ");
                if (model.company_id.IfNotNull())
                    strSql.Append(" and company_id=@company_id");
                if (model.wuliu_id.IfNotNull())
                    strSql.Append(" and wuliu_id=@wuliu_id");
                if (model.contract_flag.IfNotNull())
                    strSql.Append(" and contract_flag=@contract_flag");
                if (model.contract_state.IfNotNull())
                    strSql.Append(" and contract_state=@contract_state");
                var num = conn.ExecuteScalar(strSql.ToString(), model);
                return Convert.ToInt32(num);
            }
        }

        public bool CancelContract(int id)
        {
            using (var conn = ConnectionHelper.OpenConnection())
            {
                var sql = "update wuliu_contract_base set contract_flag=10 where id=@id";
                return conn.Execute(sql, new { id }) == 1;
            }
        }

        public wuliu_contract_base GetContract(int id)
        {
            using (var conn = ConnectionHelper.OpenConnection())
            {

                return conn.Get<wuliu_contract_base>(id);
            }
        }
    }
}
